package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.StockCheckTask;
import com.geek.factory.result.Result;
import com.geek.factory.service.IStockCheckAdjustmentService;
import com.geek.factory.service.IStockCheckTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库存盘点任务管理控制器
 */
@RestController
@RequestMapping("/stock-check-task")
@Api(tags = "后台系统的 - 库存盘点任务模块")
@Slf4j
@CrossOrigin
public class StockCheckTaskController {

    @Autowired
    private IStockCheckTaskService stockCheckTaskService;

    @Autowired
    private IStockCheckAdjustmentService adjustmentService;

    @ApiOperation("通过ID查询库存盘点任务信息")
    @GetMapping("/{taskId}")
    public Result findStockCheckTaskById(@ApiParam("任务ID") @PathVariable("taskId") Integer taskId) {
        StockCheckTask stockCheckTask = stockCheckTaskService.getById(taskId);
        log.info("stockCheckTask: {}", stockCheckTask);
        if (stockCheckTask != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", stockCheckTask);
        }
        return new Result(SuccessConstant.FAIL, "库存盘点任务记录不存在");
    }

    @ApiOperation("新增库存盘点任务")
    @PostMapping
    public Result addStockCheckTask(@RequestBody StockCheckTask stockCheckTask) {
        // 设置默认值
        stockCheckTask.setStatus(StockCheckTask.STATUS_ASSIGNED);
        stockCheckTask.setCompletedItems(0);
        stockCheckTask.setCreatedTime(LocalDateTime.now());

        boolean isSuccess = stockCheckTaskService.save(stockCheckTask);
        log.info("新增库存盘点任务: {}, 结果: {}", stockCheckTask, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", stockCheckTask);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    @ApiOperation("根据ID删除库存盘点任务")
    @DeleteMapping("/{taskId}")
    public Result deleteStockCheckTask(@ApiParam("任务ID") @PathVariable("taskId") Integer taskId) {
        // 检查任务状态，只有待执行状态才能删除
        StockCheckTask stockCheckTask = stockCheckTaskService.getById(taskId);
        if (stockCheckTask == null) {
            return new Result(SuccessConstant.FAIL, "任务记录不存在");
        }
        if (!StockCheckTask.STATUS_ASSIGNED.equals(stockCheckTask.getStatus())) {
            return new Result(SuccessConstant.FAIL, "只能删除待执行状态的任务");
        }

        boolean isSuccess = stockCheckTaskService.removeById(taskId);
        log.info("删除库存盘点任务ID: {}, 结果: {}", taskId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("批量删除库存盘点任务")
    @DeleteMapping("/batch")
    public Result batchDeleteStockCheckTask(@RequestBody Map<String, List<Integer>> request) {
        List<Integer> taskIds = request.get("taskIds");
        if (taskIds == null || taskIds.isEmpty()) {
            return new Result(SuccessConstant.FAIL, "请选择要删除的任务记录");
        }

        // 检查所有记录是否都是待执行状态
        List<StockCheckTask> stockCheckTasks = stockCheckTaskService.listByIds(taskIds);
        for (StockCheckTask task : stockCheckTasks) {
            if (!StockCheckTask.STATUS_ASSIGNED.equals(task.getStatus())) {
                return new Result(SuccessConstant.FAIL, "只能删除待执行状态的任务");
            }
        }

        boolean isSuccess = stockCheckTaskService.removeByIds(taskIds);
        log.info("批量删除库存盘点任务IDs: {}, 结果: {}", taskIds, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "批量删除成功");
        }
        return new Result(SuccessConstant.FAIL, "批量删除失败");
    }

    @ApiOperation("修改库存盘点任务信息")
    @PutMapping("/{taskId}")
    public Result updateStockCheckTask(@ApiParam("任务ID") @PathVariable("taskId") Integer taskId, @RequestBody StockCheckTask stockCheckTask) {
        stockCheckTask.setTaskId(taskId);

        boolean isSuccess = stockCheckTaskService.updateById(stockCheckTask);
        log.info("修改库存盘点任务: {}, 结果: {}", stockCheckTask, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", stockCheckTask);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("更新任务状态")
    @PutMapping("/{taskId}/status")
    public Result updateTaskStatus(
            @ApiParam("任务ID") @PathVariable("taskId") Integer taskId,
            @RequestBody Map<String, String> request
    ) {
        String status = request.get("status");
        if (StringUtils.isBlank(status)) {
            return new Result(SuccessConstant.FAIL, "状态不能为空");
        }

        StockCheckTask stockCheckTask = stockCheckTaskService.getById(taskId);
        if (stockCheckTask == null) {
            return new Result(SuccessConstant.FAIL, "任务记录不存在");
        }

        // 转换状态值
        String newStatus;
        switch (status.toLowerCase()) {
            case "待执行":
            case "待开始":
                newStatus = StockCheckTask.STATUS_ASSIGNED;
                break;
            case "进行中":
                newStatus = StockCheckTask.STATUS_IN_PROGRESS;
                break;
            case "已完成":
                newStatus = StockCheckTask.STATUS_COMPLETED;
                break;
            default:
                return new Result(SuccessConstant.FAIL, "无效的状态值");
        }

        stockCheckTask.setStatus(newStatus);

        boolean isSuccess = stockCheckTaskService.updateById(stockCheckTask);
        log.info("更新任务状态: ID={}, 状态={}, 结果={}", taskId, status, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "状态更新成功", stockCheckTask);
        }
        return new Result(SuccessConstant.FAIL, "状态更新失败");
    }

    @ApiOperation("更新任务进度")
    @PutMapping("/{taskId}/progress")
    public Result updateTaskProgress(
            @ApiParam("任务ID") @PathVariable("taskId") Integer taskId,
            @RequestBody Map<String, Integer> request
    ) {
        Integer completedItems = request.get("completedItems");
        if (completedItems == null) {
            return new Result(SuccessConstant.FAIL, "完成数量不能为空");
        }

        StockCheckTask stockCheckTask = stockCheckTaskService.getById(taskId);
        if (stockCheckTask == null) {
            return new Result(SuccessConstant.FAIL, "任务记录不存在");
        }

        stockCheckTask.setCompletedItems(completedItems);

        // 如果完成数量等于分配数量，自动设置为已完成状态
        if (completedItems >= stockCheckTask.getAssignedItems()) {
            stockCheckTask.setStatus(StockCheckTask.STATUS_COMPLETED);
        } else if (completedItems > 0) {
            stockCheckTask.setStatus(StockCheckTask.STATUS_IN_PROGRESS);
        }

        boolean isSuccess = stockCheckTaskService.updateById(stockCheckTask);
        log.info("更新任务进度: ID={}, 完成数量={}, 结果={}", taskId, completedItems, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "进度更新成功", stockCheckTask);
        }
        return new Result(SuccessConstant.FAIL, "进度更新失败");
    }

    @ApiOperation("根据盘点单ID查询任务列表")
    @GetMapping("/check/{checkId}")
    public Result getTasksByCheckId(@ApiParam("盘点单ID") @PathVariable("checkId") Integer checkId) {
        QueryWrapper<StockCheckTask> wrapper = new QueryWrapper<>();
        wrapper.eq("check_id", checkId);
        wrapper.orderByDesc("created_time");

        List<StockCheckTask> tasks = stockCheckTaskService.list(wrapper);
        return new Result(SuccessConstant.SUCCESS, "查询成功", tasks);
    }

    @ApiOperation("分页查询库存盘点任务列表")
    @GetMapping("/page")
    public Result getStockCheckTaskPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer checkId,
            @RequestParam(required = false) String assignee,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String assignedArea
    ) {
        QueryWrapper<StockCheckTask> wrapper = new QueryWrapper<>();
        if (checkId != null) {
            wrapper.eq("check_id", checkId);
        }
        if (StringUtils.isNotBlank(assignee)) {
            wrapper.like("assignee", assignee);
        }
        if (StringUtils.isNotBlank(status)) {
            // 转换状态值
            String dbStatus;
            switch (status.toLowerCase()) {
                case "待执行":
                case "待开始":
                    dbStatus = StockCheckTask.STATUS_ASSIGNED;
                    break;
                case "进行中":
                    dbStatus = StockCheckTask.STATUS_IN_PROGRESS;
                    break;
                case "已完成":
                    dbStatus = StockCheckTask.STATUS_COMPLETED;
                    break;
                default:
                    dbStatus = status;
            }
            wrapper.eq("status", dbStatus);
        }
        if (StringUtils.isNotBlank(assignedArea)) {
            wrapper.like("assigned_area", assignedArea);
        }
        wrapper.orderByDesc("created_time");

        Page<StockCheckTask> page = stockCheckTaskService.page(new Page<>(pageNum, pageSize), wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有库存盘点任务列表")
    @GetMapping("/list")
    public Result getAllStockCheckTasks() {
        List<StockCheckTask> stockCheckTasks = stockCheckTaskService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", stockCheckTasks);
    }

    @ApiOperation("获取任务统计信息")
    @GetMapping("/stats/{checkId}")
    public Result getStockCheckTaskStats(@ApiParam("盘点单ID") @PathVariable("checkId") Integer checkId) {
        Map<String, Object> stats = stockCheckTaskService.getTaskStats(checkId);
        return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
    }
}